package com.czk.zookeeper.curator.getchild;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/7 21:45
 */
public class CuratorGetChildTest {
    String IP = "192.168.25.133:2181,192.168.25.133:2182,192.168.25.133:2183";
    CuratorFramework client;

    @Before
    public void before() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString(IP)
                .sessionTimeoutMs(50000)
                .retryPolicy(retryPolicy)
                .build();
        client.start();
    }

    @After
    public void after() {
        client.close();
    }

    /**
     * 获取其所有子节点
     *
     * @throws Exception
     */
    @Test
    public void test1() throws Exception {
        List<String> list = client.getChildren()
                // 节点路径
                .forPath("/create");
        for (String s : list) {
            System.out.println(s);
        }
    }

    /**
     * 异步方式读取子节点
     *
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {
        client.getChildren()
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                        // 节点路径
                        System.out.println(curatorEvent.getPath());
                        // 事件类型
                        System.out.println(curatorEvent.getType());
                        // 读取子节点数据
                        List<String> children = curatorEvent.getChildren();
                        for (String child : children) {
                            System.out.println(child);
                        }
                    }
                })
                .forPath("/create");
        Thread.sleep(5000);
        System.out.println("结束");
    }

    @Test
    public void test3() throws Exception {

    }

}
